package com.aya.copy.tools.action;

import com.intellij.database.datagrid.*;
import com.intellij.database.editor.DatabaseTableFileEditor;
import com.intellij.ide.util.TreeJavaClassChooserDialog;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.DataContext;
import com.intellij.openapi.actionSystem.PlatformDataKeys;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.ui.DialogWrapper;
import com.intellij.openapi.ui.Messages;
import com.intellij.psi.PsiClass;

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.util.List;

import static com.intellij.openapi.ui.Messages.getCancelButton;
import static com.intellij.openapi.ui.Messages.getOkButton;

public class GenerateCheckSqlAction extends AnAction {


    @Override
    public void actionPerformed(AnActionEvent e) {

        TreeJavaClassChooserDialog treeJavaClassChooserDialog =
                new TreeJavaClassChooserDialog("选择映射的JavaBean", e.getProject());
        treeJavaClassChooserDialog.show();
        PsiClass selectedClass = treeJavaClassChooserDialog.getSelected();
        // 没有选择类
        if (selectedClass == null) {
            return;
        }

        DataContext dataContext = e.getDataContext();

        FileEditor fileEditor = PlatformDataKeys.FILE_EDITOR.getData(dataContext);
        // 类型不匹配
        if (!(fileEditor instanceof DatabaseTableFileEditor)) {
            return;
        }
        DatabaseTableFileEditor databaseTableFileEditor = (DatabaseTableFileEditor) fileEditor;
        DataGrid dataGrid = databaseTableFileEditor.getDataGrid();

        DatabaseGridDataHookUp databaseHookUp = DataGridUtil.getDatabaseHookUp(dataGrid);
        DataGridListModel model = databaseHookUp.getModel();
        List<DataConsumer.Column> columns = model.getColumns();

        List<DataConsumer.Row> selectedRows = DataGridUtil.getSelectedRows(dataGrid);

        GridProcessor gridProcessor = new GridProcessor();
        String context = gridProcessor.process(selectedClass, selectedRows, columns);

        Messages.InputDialog dialog = new Messages.MultilineInputDialog(null, "将以下内容复制到剪切板", "转换的bean", null, context, null,
                new String[]{getOkButton(), getCancelButton()}, 0);
        dialog.show();
        if (dialog.getExitCode() == DialogWrapper.OK_EXIT_CODE) {

            Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
//设置字符串
//构建String数据类型
            StringSelection selection = new StringSelection(dialog.getInputString());
//添加文本到系统剪切板
            clipboard.setContents(selection, null);
        }

    }


}
